package org.easy.http.client.http;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

import java.io.File;
import java.io.IOException;

/**
 * @Description TODO
 * @Author WuXueLi
 * @Date 19:11 2023/2/25
 * @Version 1.0
 **/
public class FileRequestBody extends RequestBody {

    private final File file;

    private final MediaType mediaType;

    public FileRequestBody (File file,MediaType mediaType) {
        this.file = file;
        this.mediaType = mediaType;
    }

    @Override
    public long contentLength() throws IOException {
        return this.file.length();
    }

    @Override
    public MediaType contentType() {
        return this.mediaType;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {

        Source source = null;
        try {
            source = Okio.source(this.file);
            sink.writeAll(source);
        } finally {
            Util.closeQuietly(source);
        }

    }
}
